import React, { Component } from 'react';
import {
	Text,
	View,
	StyleSheet,
	RefreshControl,
	TouchableOpacity,
	DeviceEventEmitter,
	ScrollView,
	WebView,
	Animated,
	TouchableHighlight,
	TextInput,
	findNodeHandle,
	KeyboardAvoidingView,
	Keyboard
} from 'react-native';
import { connect } from 'react-redux';
import { Actions } from 'react-native-router-flux';
import ViewUtils from '../utils/ViewUtils';
import DeviceUtils from '../utils/DeviceUtils';
import NavigationBar from '../components/NavigationBar';
import actioncoll from '../actions';
import BasicComment from './comment';

class todo extends Component {
	constructor(props) {
		super(props);
		this.state = {
			height: DeviceUtils.deviceHeight,
			offset: new Animated.Value(DeviceUtils.deviceHeight),
			X_Dimension: '',
			Y_Dimension: '',
			Child_View_Width: '',
			Child_View_Height: '',
			comment:''
		};
		this.y = 30;
		
	}
	openModal(toValue=DeviceUtils.deviceHeight - 50,duration=200) {
		Animated.timing(this.state.offset, {
			duration: duration,
			toValue: toValue,
		}).start();
	}
	closeModal(toValue=DeviceUtils.deviceHeight - 50,duration=200) {
		Animated.timing(this.state.offset, {
			duration: 200,
			toValue: toValue,
		}).start();
	}

	calculate_ChildView_Dimension = () => {
		this.refs.Child_View.measureLayout(
			ReactNative.findNodeHandle(this.refs.scroll),
			(X_Position, Y_Position, Width, Height) => {
				this.setState({
					X_Dimension: X_Position,

					Y_Dimension: Y_Position,

					Child_View_Height: Width,

					Child_View_Width: Height,
				});
				console.log('state:', this.state);
			}
		);
	};

	onBasicCommentLayout(event) {
		console.log('layout:', event.nativeEvent.layout);
		this.calculate_ChildView_Dimension();
	}
	_reset() {
		
    }

    _onFocus(refName) {
		
	}
	addComment(){
		if(this.state.comment == ''){
			alert('请填写评论')
		}else{
			this.props.AddArticleComment(this.props.news.ID, this.state.comment)
			this.setState({
				comment: '',
				commentValue: ''
			})
			
		}
		
	}
	keyboardWillShow(e){
		this.openModal(DeviceUtils.deviceHeight - e.endCoordinates.height  - 50,e.duration)
    }

    keyboardWillHide(e){
		this.openModal(DeviceUtils.deviceHeight - 50,e.duration)
    }
	componentDidMount() {
		this.props.GetArticleForMobileByID(this.props.news.ID);
	}
	componentWillMount(){
		this.keyboardWillShowListener = Keyboard.addListener('keyboardWillShow', this.keyboardWillShow.bind(this));
        this.keyboardWillHideListener = Keyboard.addListener('keyboardWillHide', this.keyboardWillHide.bind(this));
	}
	componentWillUnmount() {
		clearTimeout(this.timer)
		this.keyboardWillShowListener.remove();
        this.keyboardWillHideListener.remove();
	}

	render() {
		var content = unescape(this.props.article.CONTENT);

		return (
			// <View style={styles.container}>
			 //behavior= height， padding， position
			<KeyboardAvoidingView
			style={styles.container}
			behavior="padding"
		  >
				<NavigationBar leftButton={ViewUtils.getLeftButton(() => Actions.pop())} title="待办" />
				<ScrollView
					ref='scroll'
					style={{ borderColor: 'red', borderWidth: 2, }}
					// contentContainerStyle={{paddingLeft:20,paddingTop:20,paddingRight:20}}
					keyboardDismissMode="on-drag"
					keyboardShouldPersistTaps="never"
					showsVerticalScrollIndicator={true}
					scrollEnabled={true}
					// pagingEnabled={true}
					horizontal={false}
					scrollEventThrottle={200}
					onContentSizeChange={(contentWidth, contentHeight) => {}}
					onScroll={e => {
						if (e.nativeEvent.contentOffset.y + DeviceUtils.deviceHeight >= this.state.Y_Dimension) {
							this.openModal(DeviceUtils.deviceHeight-50);
						} else {
							this.closeModal(DeviceUtils.deviceHeight);
						}
						this.y = e.nativeEvent.contentOffset.y
						
					}}
				>
					<View style={styles.header}>
						<Text style={styles.title}>{this.props.article.TITLE}</Text>
					</View>

					<WebView
						scrollEnabled={false}
						automaticallyAdjustContentInsets={true}
						contentInset={{ top: 0, left: 0 }}
						scalesPageToFit={true}
						source={{
							html: `<!DOCTYPE html><html><head><meta id="viewport" name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1; user-scalable=no;"></head><body>${content}<script>window.onload=function(){window.location.hash = 1;document.title = document.body.clientHeight;}</script></body></html>`,
							baseUrl: 'http://202.106.90.110:81/',
						}}
						automaticallyAdjustContentInsets={false}
						style={{
							flex: 1,
							width: DeviceUtils.deviceWidth,
							height: this.state.height,
							backgroundColor: '#fff',
						}}
						//  width: DeviceUtils.deviceWidth, height: DeviceUtils.deviceHeight
						javaScriptEnabled={true}
						domStorageEnabled={true}
						decelerationRate="normal"
						//  contentInset={{left: 10, right: 10}}
						onNavigationStateChange={title => {
							if (title.title != undefined) {
								this.setState({
									height: parseInt(title.title) + 20,
								});
							}	
						}}
						onLoadEnd = {()=>{
							
							this.timer = setTimeout(()=>{
								this.calculate_ChildView_Dimension()
								
								if(this.state.Y_Dimension != '' && this.state.Y_Dimension < DeviceUtils.deviceHeight){
									this.openModal()
								}
							},1000)
							
						}}

						//  onShouldStartLoadWithRequest={this.onShouldStartLoadWithRequest}
						//  startInLoadingState={true}
					/>
					<View style={styles.commentView} ref="Child_View">
						<Text style={styles.commentTitle}>
							评论
						</Text>
						<BasicComment articleId={this.props.news.ID} />
					</View>
				</ScrollView>
				<Animated.View style={[styles.animatedContainer, { transform: [{ translateY: this.state.offset }] }]}>
					<KeyboardAvoidingView style={styles.toastStyle}>
						<TextInput
						ref="textInput"
							style={{ height: 50, width: DeviceUtils.deviceWidth - 50, padding: 4 }}
							maxLength={140}
							multiline={true}
							numberOfLines={4}
							placeholder="说点什么吧..."
							onBlur={this._reset.bind(this)}
							onFocus={this._onFocus.bind(this, 'textInput')}
							onChangeText={text=>{
								this.setState({
									comment: text,
									commentValue: text
								})
							}}
							// onSubmitEditing={()=>this.addComment()}
							onSubmitEditing={(e)=>{
								this.addComment()
								this.refs.textInput.blur()
							}}
							returnKeyType='send'
							value={this.state.commentValue}
						/>
						<TouchableHighlight onPress={() => this.addComment()}>
							<Text style={{ color: 'cyan' }}>发送</Text>
						</TouchableHighlight>
					</KeyboardAvoidingView>
					
				</Animated.View>
				</KeyboardAvoidingView>
			//</View>
		);
	}
}

const styles = StyleSheet.create({
	container: {
		flex: 1,
		backgroundColor: '#fff',
	},
	header: {
		// flex: 1,
		justifyContent: 'center',
		alignItems: 'center',
		padding: 10,
	},
	title: {
		fontSize: 20,
		fontWeight: 'bold'
	},
	webView: {
		width: ViewUtils.deviceWidth,
		height: 200,
	},
	commentView: {
		alignItems: 'center',
		marginTop: 20,
		backgroundColor: '#fff',
		padding: 10,
		width: DeviceUtils.deviceWidth,
		shadowColor: 'gray',
		shadowOffset: { width: 5, height: -2 },
		shadowRadius: 3,
		shadowOpacity: 0.6,
	},
	commentTitle: {
		fontSize: 18,
	},
	animatedContainer: {
		position: 'absolute',
		top: 0,
		bottom: 0,
		left: 0,
		right: 0,
		backgroundColor: 'white',
		justifyContent: 'center',
		alignItems: 'center',
		width: DeviceUtils.deviceWidth,
		height: 50,
		shadowColor: 'gray',
		shadowOffset: { width: 5, height: -2 },
		shadowRadius: 3,
		shadowOpacity: 0.6,
	},
	toastStyle: {
		flex: 1,
		flexDirection: 'row',
		justifyContent: 'center',
		alignItems: 'center',
		backgroundColor: 'white',
	},
});

export default connect(
	state => ({
		article: state.todoReducer.article,
	}),
	dispatch => ({
		GetArticleForMobileByID: articleId => dispatch(actioncoll.todo.GetArticleForMobileByID(articleId)),
		AddArticleComment:(articleId, content) => dispatch(actioncoll.AddArticleComment (articleId, content))
	})
)(todo);
